<script setup>

import moduleJson from "@/components/page/moduleJson"
import dataJson from "@/components/page/dataJson"
import {inject, nextTick, onMounted, reactive, ref, toRaw, toRefs, unref} from "vue";
import {CloseBold, Delete, EditPen, Plus} from "@element-plus/icons-vue";
import AgentsService from "@/service/impl/AgentsService.js";
import AgentsClassModel from "@/model/AgentsClassModel.js";
import AgentsInfoModel from "@/model/AgentsInfoModel.js";
import Dialog from "@/components/dialog/Dialog.vue";
import dialogJson from "@/components/dialog/dialogJson.js";
import FileUploadService from "@/service/impl/FileUploadService.js";


const t = inject('$t')
const message = inject('message')
const data = dataJson()
const module = moduleJson()
const agentsInfoModel = ref(new AgentsInfoModel())
const pageTable = ref()
const loading = ref(false)
const activeName = ref('base')
const url = window.webConfig.apiUrl()
const models = ref([])
const modelsInfo = ref([])
const knowledge = ref([])
const mcpList = ref([])


const infoList = () => {
    AgentsService.infoList(data.value.source()).then(res => {
        data.value.list = res.data
        loading.value = false
    }).catch(e => loading.value = false)
}

const delInfo = (obj) => {
    AgentsService.infoDel(obj).then(res => {
        message.success("删除成功")
        infoList()
    })
}

const onAddAgents = (item,index,type) => {
    activeName.value = 'base'
    module.value.width = '40%'
    module.value.dialog.show = true
    module.value.dialog.load = false
    initConfig(() => {
        if(item){
            module.value.title = '编辑智能体'
            agentsInfoModel.value = JSON.parse(JSON.stringify(item))
            return
        }
        agentsInfoModel.value = new AgentsInfoModel()
        module.value.title = '添加智能体'
    })
}

const initConfig = (fun) => {
    AgentsService.agentsConfig({}).then(res => {
        module.value.dialog.load = false
        modelsInfo.value = res.data.modelConfigVOS || []
        models.value = res.data.modelClassVOS || []
        knowledge.value = res.data.knowledgeClassVOS || []
        mcpList.value = res.data.mcpList || []
        if(fun){
            fun()
        }
    }).catch(e => {
        module.value.dialog.load = false
    })
}


const infoConfirm = () => {
    module.value.dialog.load = true
    AgentsService.infoEdit(agentsInfoModel.value).then(res => {
        message.success("编辑成功")
        module.value.dialog.load = false
        infoList()
    }).catch(e => {
        module.value.dialog.show = false
    })
}


const onChangeAvatar = () => {
    let input = document.createElement("input");
    input.type = "file";
    input.accept = "image/*";
    input.onchange = (event) => {
        let file = event.target.files[0];
        if (file) {
            FileUploadService.toLocal({
                file: file,
                path: 'avatar'
            }).then(res => {
                agentsInfoModel.value.avatar = res.data
            })
        }
    };
    input.click();
}


const addSynergismAgent = (array) => {
    let item = {
        agent: null,
        prompt: null
    }
    array.push([item])
}
const addAgentItem = (array) => {
    let item = {
        agent: null,
        prompt: null
    }
    array.push(item)
}
const delAgentItem = (array,idx,index) => {
    array.length > 0 && array.splice(idx, 1)
    array.length === 0 && agentsInfoModel.value.config.synergism.splice(index, 1)
}

onMounted(() => {
    module.value.layout = {
        tableLeft: false,
        width: "0px",
        table: false,
    }
    module.value.page = false
    module.value.init(AgentsService.url.infoEdit, AgentsService.url.infoEdit,
        AgentsService.url.titleDel, null, null)
    module.value.operations.width = "200px"
    module.value.dialog.width = "50%"
    infoList()
})

</script>
<template>
    <Page
        @refresh="infoList"
        @edit-open="onAddAgents"
        @edit-confirm="infoConfirm"
        :data="data"
        :module="module"
        ref="pageTable"
    >
        <template #table>
            <el-row class="card-c" v-loading="loading">
                <el-row v-for="(item,index) in data.list" style="position: relative">
                    <el-popconfirm title="确认要删除吗?" @confirm="delInfo(item)">
                        <template #reference>
                            <el-icon class="item-del"><CircleCloseFilled /></el-icon>
                        </template>
                    </el-popconfirm>
                    <el-card >
                        <template #header>
                            <el-row @click="onAddAgents(item,index,0)">
                                <el-col :span="12">
                                    <el-row class="avatar"><el-avatar shape="square"  :src="url + item.avatar" /></el-row>
                                </el-col>
                                <el-col :span="12">
                                    <el-row class="name">{{item.name}}</el-row>
                                </el-col>
                            </el-row>
                        </template>
                        <el-row class="ellipsis">
                            {{item.background}}
                        </el-row>
                    </el-card>
                </el-row>
            </el-row>
        </template>
        <template #table-left>
        </template>
        <template #operate-before>
        </template>
        <template #operate-after>
        </template>
        <template #table-column>

        </template>
        <template #after-table-event="row">
        </template>
        <template #table-dialog>
            <el-form :rules="agentsInfoModel" :label-width="110" :label-position="'left'"
                     :model="agentsInfoModel" style="width: 100%;">
                <el-tabs v-model="activeName" >
                    <el-tab-pane label="智能体信息" name="base">
                        <el-form-item label="智能体头像" prop="avatar">
                            <el-avatar shape="square"  :src="url + agentsInfoModel.avatar" @click="onChangeAvatar" />
                        </el-form-item>
                        <el-form-item label="智能体名称" prop="name">
                            <el-input v-model="agentsInfoModel.name" autocomplete="off"/>
                        </el-form-item>
                        <el-form-item label="智能体背景" prop="background">
                            <el-input
                                v-model="agentsInfoModel.background"
                                :rows="3"
                                resize="none"
                                maxlength="500"
                                type="textarea"
                            />
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="选用模型" name="models">
                        <el-form-item :label="item.className" :prop="item.filedName" v-for="item in models">
                            <el-select v-model="agentsInfoModel.config.model[item.filedName]" :key="item.id">
                                <el-option
                                    v-for="config in modelsInfo.filter(i => i.classType === item.classType) || []"
                                    :key="config.id"
                                    :label="config.name"
                                    :value="config.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="选用知识库" name="knowledge">
                        <el-checkbox-group v-model="agentsInfoModel.config.knowledges">
                            <el-checkbox v-for="item in knowledge" :label="item.title" :value="item.id" />
                        </el-checkbox-group>
                    </el-tab-pane>
                    <el-tab-pane label="选用工具" name="tool">
                        <el-checkbox-group v-model="agentsInfoModel.config.tools">
                            <el-checkbox v-for="item in mcpList" :label="item.title" :value="item.id" />
                        </el-checkbox-group>
                    </el-tab-pane>
                    <el-tab-pane label="Agent协同" name="synergism">
                        <el-alert type="info" :closable="false">
                            Agent顺序按照添加顺序执行，每一个的输入为上一个执行后的输出
                        </el-alert>
                        <el-button type="primary" size="small" style="margin-top: 5px;"
                                   @click="addSynergismAgent(agentsInfoModel.config.synergism)">添加Agent</el-button>
                        <el-form-item label="选择Agent" v-for="(agents,index) in agentsInfoModel.config.synergism">
                            <el-row style="width: 100%" v-for="(item,idx) in agents">
                                <el-col :span="6">
                                    <el-select placeholder="选择Agent" size="small" v-model="item.agent">
                                        <el-option
                                            v-for="item in data.list "
                                            :key="item.id"
                                            :label="item.name"
                                            :value="item.id"
                                        />
                                    </el-select>
                                </el-col>
                                <el-col :span="1" />
                                <el-col :span="13">
                                    <el-input size="small" placeholder="提示词" v-model="item.prompt"></el-input>
                                </el-col>
                                <el-col :span="1" />
                                <el-col :span="3">
                                    <el-button type="danger" size="small" @click="delAgentItem(agents,idx,index)">删除</el-button>
                                </el-col>
                            </el-row>
                            <el-button type="primary" size="small" @click="addAgentItem(agents)">添加</el-button>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </template>
        <template #table-search>

        </template>

    </Page>

<!--    <Dialog :dialog="infoDialog" >-->

<!--    </Dialog>-->

</template>

<style lang="scss" scoped>
.card-c{
    width: 100%;height: 100%;overflow-y: auto;gap: 5px;align-content: start;
    .item-del{
        position: absolute;
        top: 0;
        right: -5px;
        z-index: 999;
        cursor: pointer;
    }
}
:deep(.el-card){
    padding: 0px !important;
    width: 200px;
}
:deep(.el-card__header){
    cursor: pointer;
    padding: 5px !important;
    > el-row{
        width: 100%;height: 50px;
    }
    .avatar{
        width: 100%;height: 50px;justify-content: start;align-content: center
    }
    .name{
        width: 100%;height: 50px;justify-content: end;align-content: center;font-size: 1em
    }
}
:deep(.el-card__body){
    padding: 5px !important;
}
.ellipsis{
    display: -webkit-box !important;
    -webkit-box-orient: vertical !important;
    -webkit-line-clamp: 3 !important;
    overflow: hidden !important;
    text-overflow: ellipsis !important;
    word-break: break-all; /* 强制长单词换行 */
    font-size: 14px;
    line-height: 1.5;
    height: calc(14px * 1.5 * 3);
}
</style>
